﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Common.Background.Controllers
{
    using EntityFrameworks.Data.Core;

    using Common.Background.BLL;
    using EntityFrameworks.Entity.Core;
    using EntityFrameworks.Entity.Core.CommonEnums;
    [Common.Background.Filter.AuthorizationFilter]
    public partial class DepartmentController : BaseController
    {
        public DepartmentController()
            : base(new backgroundEntities())
        {
        }
        //
        // GET: /Department/

        public ActionResult Index(string deptName, int? page)
        {
            var deptManager = new DeptManager();
            var model = deptManager.GetDept(
                new DeptSpecification(deptName),
                new PageParameters(page ?? 1, base.PageSize));
            return View(model);
        }

        //
        // GET: /Department/Details/5

        public ActionResult Details(int id)
        {
            return View(DeptRepository.Find(id));
        }

        //
        // GET: /Department/Create

        public ActionResult Create(int id)
        {
            ViewBag.DeptLevel = DeptRepository.Find(id).DeptLevel;
            return View();
        }

        //
        // POST: /Department/Create

        [HttpPost]
        public ActionResult Create(WebDepartments entity)
        {
            try
            {
                entity.UpdateDate = DateTime.Now;
                entity.Status = Status.Normal.GetHashCode();
                entity.DeptLevel += 1;
                entity.Operator = base.CurrentUserName;
                DeptRepository.Insert(entity);

                return RedirectToAction("Index", new { flag = 1 });
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Department/Edit/5

        public ActionResult Edit(int id)
        {
            return View(DeptRepository.Find(id));
        }

        //
        // POST: /Department/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var entity = DeptRepository.Find(id);
            TryUpdateModel(entity);
            DeptRepository.Update(entity);
            return RedirectToAction("Index", new { flag = 1 });
        }

        //
        // GET: /Department/Delete/5

        public ActionResult Delete(int id)
        {
            DeptRepository.Update<WebDepartments>(i => new WebDepartments
            {
                DepartmentID = id,
                Status = Status.Deleted.GetHashCode()
            });
            return RedirectToAction("Index", new { flag = 1 });
        }


    }
}
